
from translate import Translator

def translate_from_file(file_path, output_file=None):
    """
    读取txt文件并逐行翻译
    :param file_path: 输入文件路径
    :param output_file: 可选，输出文件路径。如果提供，结果将写入文件
    :return: 翻译结果列表
    """
    translator = Translator(to_lang="zh")
    results = []
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        for line in lines:
            line = line.strip()
            if line:  # 跳过空行
                translation = translator.translate(line)
                print(f"原文: {line} -> 翻译: {translation}")
                results.append(translation)
                
        if output_file:
            with open(output_file, 'w', encoding='utf-8') as f:
                for result in results:
                    f.write(result + '\n')
            print(f"\n翻译结果已保存到: {output_file}")
            
        return results
        
    except Exception as e:
        print(f"发生错误: {e}")
        return None

# 示例使用
if __name__ == "__main__":
    input_file = "input.txt"  # 你的输入文件
    output_file = "output.txt"  # 可选输出文件
    translate_from_file(input_file, output_file)